package cn.tedu.egweibo1.controller;

import cn.tedu.egweibo1.mapper.UserMapper;
import cn.tedu.egweibo1.pojo.dto.UserLoginDTO;
import cn.tedu.egweibo1.pojo.dto.UserRegDTO;
import cn.tedu.egweibo1.pojo.entity.User;
import cn.tedu.egweibo1.pojo.vo.UserSelectByIdVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.util.Date;

@RestController
@RequestMapping("/v1/users/")
public class UserController {
    @Autowired
    private UserMapper userMapper;

    @PostMapping("reg")
    public int insert(@RequestBody UserRegDTO userRegDTO){
        UserSelectByIdVO userSelectByIdVO = userMapper.userSelectById(userRegDTO.getUsername());
        if (userSelectByIdVO != null){
            return 2;
        }
        User user = new User();
        BeanUtils.copyProperties(userRegDTO,user);
        user.setCreated(new Date());
        userMapper.reg(user);
        return 1;
    }

    @PostMapping("login")
    public int login(@RequestBody UserLoginDTO userLoginDTO, HttpSession session){
        UserSelectByIdVO userSelectByIdVO = userMapper.userSelectById(userLoginDTO.getUsername());
        if(userSelectByIdVO!=null){
            if (userSelectByIdVO.getPassword().equals(userLoginDTO.getPassword())){
                session.setAttribute("user",userSelectByIdVO);
                return 1;
            }
            return 2;
        }
        return 3;
    }

    @GetMapping("currentUser")
    public UserSelectByIdVO currentUser(HttpSession session){
        UserSelectByIdVO userSelectByIdVO = (UserSelectByIdVO)session.getAttribute("user");
        return userSelectByIdVO;
    }

    @GetMapping("logout")
    public void logout(HttpSession session){
        session.removeAttribute("user");
    }
}
